using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NativeWebSocket;
using System.Text;
using Newtonsoft.Json;

public class NetWebSocket : MonoBehaviour
{
    private static WebSocket websocket;

    
    
    // Start is called before the first frame update
    async void Start()
    {
        websocket = new WebSocket("ws://localhost:9999/game");

        websocket.OnOpen += () =>
        {
            Debug.Log("Connection open!");
            EventManager.getInstance().dispatcher(new NetConnectSuccessEvent("连接成功！"));
        };

        websocket.OnError += (e) =>
        {
            Debug.Log("Error! " + e);
            EventManager.getInstance().dispatcher(new NetErrorEvent(e));
        };

        websocket.OnClose += (e) =>
        {
            Debug.Log("Connection closed!");
            EventManager.getInstance().dispatcher(new NetConnectClosedEvent());
            GameObject.Destroy(PlayerManager.getInstance().mainPlayer.obj);
            PlayerManager.getInstance().mainPlayer = null;
            foreach (Player otherPlayer in PlayerManager.getInstance().ohterPlayers.Values)
            {
                GameObject.Destroy(otherPlayer.obj);
            }
            PlayerManager.getInstance().ohterPlayers.Clear();
        };

        websocket.OnMessage += (bytes) =>
        {
            Debug.Log("OnMessage!");
            string msgStr = Encoding.UTF8.GetString(bytes);
            Debug.Log(msgStr);
            MsgHandlers.getInstance().handleMsg(msgStr);
            // getting the message as a string
            // var message = System.Text.Encoding.UTF8.GetString(bytes);
            // Debug.Log("OnMessage! " + message);
        };

        // Keep sending messages at every 0.3s
        // InvokeRepeating("SendWebSocketMessage", 0.0f, 0.3f);

        // waiting for messages
        
        EventManager.getInstance().register(EventIdDefine.NetConnect, (e) => { connect();});
        
    }
    
    public  void connect()
    {
        if (websocket != null)
        {
             websocket.Connect();
        }
        
    }

    void Update()
    {
#if !UNITY_WEBGL || UNITY_EDITOR
        websocket.DispatchMessageQueue();
#endif
    }
     public static void SendText(string msg)
    {
        if (websocket.State == WebSocketState.Open)
        {
            // Sending bytes
            // await websocket.Send(new byte[] { 10, 20, 30 });

            // Sending plain text
             websocket.SendText("plain text message");
        }
    }
     public static void SendMsg(IMsg msg)
     {
         string msgStr = JsonConvert.SerializeObject(msg);
         Debug.Log("发送消息："+msgStr);
         if (websocket.State == WebSocketState.Open)
         {
             // Sending bytes
             // await websocket.Send(new byte[] { 10, 20, 30 });

             // Sending plain text
             websocket.SendText(msgStr);
         }
     }
    async void SendWebSocketMessage()
    {
        if (websocket.State == WebSocketState.Open)
        {
            // Sending bytes
            await websocket.Send(new byte[] { 10, 20, 30 });

            // Sending plain text
            await websocket.SendText("plain text message");
        }
    }

    private async void OnApplicationQuit()
    {
        await websocket.Close();
    }
}
